#include "rc522.h"

#define MAXRLEN 18

#if SPI_MODE == HardWare

void RC522_SPI_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Pin = RC522_MISO_PIN | RC522_MOSI_PIN | RC522_SCK_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    
    GPIO_InitStructure.GPIO_Pin = RC522_NSS_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    
    SPI_InitTypeDef SPI_InitStructure;
    SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
    SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
    SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
    SPI_InitStructure.SPI_CRCPolynomial = 7;
    SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
    SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
    SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
    
    SPI_Init(SPI1, &SPI_InitStructure);
    SPI_Cmd(SPI1, ENABLE);
}


uint8_t SPI_ReadWriteByte(uint8_t TxData)
{
    uint16_t timeout = 720;
    //等待发送缓冲区清空
    while((SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET) && timeout)   timeout--;
    SPI_I2S_SendData(SPI1, TxData); //通过外设SPIx发送一个byte数据
    timeout = 720;
    //等待接收缓冲区非空
    while((SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET) && timeout)   timeout--;
    return SPI_I2S_ReceiveData(SPI1); //返回通过SPIx最近接收的数据
}

void RC522_Write(uint8_t Address, uint8_t value)
{
    NSS_L;
    Address = ((Address << 1) & 0x7E);
    SPI_ReadWriteByte(Address);
    SPI_ReadWriteByte(value);
    NSS_H;
}

uint8_t RC522_Read(uint8_t Address)
{
    uint8_t data;

    NSS_L;
    Address = ((Address << 1) & 0x7E) | 0x80;
    SPI_ReadWriteByte(Address);
    data = SPI_ReadWriteByte(0xff);
    NSS_H;
    return data;
}

#else

void RC522_SPI_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    //MISO
    RCC_APB2PeriphClockCmd(RC522_MISO_CLK, ENABLE);
    GPIO_InitStructure.GPIO_Pin = RC522_MISO_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(RC522_MISO_PORT, &GPIO_InitStructure);
    
    //MOSI
    RCC_APB2PeriphClockCmd(RC522_MOSI_CLK, ENABLE);
    GPIO_InitStructure.GPIO_Pin = RC522_MOSI_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(RC522_MOSI_PORT, &GPIO_InitStructure);
    //SCK
    RCC_APB2PeriphClockCmd(RC522_SCK_CLK, ENABLE);
    GPIO_InitStructure.GPIO_Pin = RC522_SCK_PIN;
    GPIO_Init(RC522_SCK_PORT, &GPIO_InitStructure);
    //NSS
    RCC_APB2PeriphClockCmd(RC522_NSS_CLK, ENABLE);
    GPIO_InitStructure.GPIO_Pin = RC522_NSS_PIN;
    GPIO_Init(RC522_NSS_PORT, &GPIO_InitStructure);
}

void RC522_Write(uint8_t Address, uint8_t value)
{
    uint8_t ucAddr= ((Address<<1)&0x7E);

    SCK_L;
    NSS_L;
    for(uint8_t i=8; i>0; i--)
    {
        if(ucAddr&0x80) MOSI_H;
        else    MOSI_L;
        SCK_H;
        ucAddr <<= 1;
        SCK_L;
    }

    for(uint8_t i=8; i>0; i--)
    {
        if(value&0x80)  MOSI_H;
        else    MOSI_L;
        SCK_H;
        value <<= 1;
        SCK_L;
    }
    NSS_H;
    SCK_H;
}

uint8_t RC522_Read(uint8_t Address)
{
    uint8_t ucAddr = ((Address<<1)&0x7E)|0x80;
    uint8_t ucResult=0;
    
    NSS_L;
    for(uint8_t i=8; i>0; i--)
    {
        SCK_L;
        if(ucAddr&0x80) MOSI_H;
        else    MOSI_L;
        SCK_H;
        ucAddr <<= 1;
    }

    for(uint8_t i=8; i>0; i--)
    {
        SCK_L;
        ucResult <<= 1;
        SCK_H;
        if(READ_MISO == 1)  ucResult |= 1;
    }

    NSS_H;
    SCK_H;
    return ucResult;
}

#endif

void RC522_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    //RST
    RCC_APB2PeriphClockCmd(RC522_RST_CLK, ENABLE);
    GPIO_InitStructure.GPIO_Pin = RC522_RST_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(RC522_RST_PORT, &GPIO_InitStructure);

    RC522_SPI_Init();

    PcdReset();
    PcdAntennaOff(); 
    PcdAntennaOn();  
    M500PcdConfigISOType( 'A' );
}

/////////////////////////////////////////////////////////////////////
//功    能：寻卡
//参数说明: req_code[IN]:寻卡方式
//                0x52 = 寻感应区内所有符合14443A标准的卡
//                0x26 = 寻未进入休眠状态的卡
//          	  pTagType[OUT]：卡片类型代码
//                0x4400 = Mifare_UltraLight
//                0x0400 = Mifare_One(S50)
//                0x0200 = Mifare_One(S70)
//                0x0800 = Mifare_Pro(X)
//                0x4403 = Mifare_DESFire
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////
char PcdRequest(unsigned char req_code,unsigned char *pTagType)
{
   char status;
   unsigned int  unLen;
   unsigned char ucComRC522Buf[MAXRLEN];
   
   ClearBitMask(Status2Reg,0x08);
   RC522_Write(BitFramingReg,0x07);
   SetBitMask(TxControlReg,0x03);
 
   ucComRC522Buf[0] = req_code;

   status = PcdComRC522(PCD_TRANSCEIVE,ucComRC522Buf,1,ucComRC522Buf,&unLen);

   if ((status == MI_OK) && (unLen == 0x10))
   {
        *(pTagType+1) = ucComRC522Buf[0];
        *pTagType = ucComRC522Buf[1];
   }
   else
   {   status = MI_ERR;   }

   return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：防冲撞
//参数说明: pSnr[OUT]:卡片序列号，4字节
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////  
char PcdAnticoll(unsigned char *pSnr)
{
    char status;
    unsigned char i,snr_check=0;
    unsigned int  unLen;
    unsigned char ucComRC522Buf[MAXRLEN]; 
    

    ClearBitMask(Status2Reg,0x08);
    RC522_Write(BitFramingReg,0x00);
    ClearBitMask(CollReg,0x80);
 
    ucComRC522Buf[0] = PICC_ANTICOLL1;
    ucComRC522Buf[1] = 0x20;

    status = PcdComRC522(PCD_TRANSCEIVE,ucComRC522Buf,2,ucComRC522Buf,&unLen);

    if (status == MI_OK)
    {
    	 for (i=0; i<4; i++)
         {   
             *(pSnr+i)  = ucComRC522Buf[i];
             snr_check ^= ucComRC522Buf[i];
         }
         if (snr_check != ucComRC522Buf[i])
         {   status = MI_ERR;    }
    }
    
    SetBitMask(CollReg,0x80);
    return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：选定卡片
//参数说明: pSnr[IN]:卡片序列号，4字节
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////
char PcdSelect(unsigned char *pSnr)
{
    char status;
    unsigned char i;
    unsigned int  unLen;
    unsigned char ucComRC522Buf[MAXRLEN]; 
    
    ucComRC522Buf[0] = PICC_ANTICOLL1;
    ucComRC522Buf[1] = 0x70;
    ucComRC522Buf[6] = 0;
    for (i=0; i<4; i++)
    {
    	ucComRC522Buf[i+2] = *(pSnr+i);
    	ucComRC522Buf[6]  ^= *(pSnr+i);
    }
    CalulateCRC(ucComRC522Buf,7,&ucComRC522Buf[7]);
  
    ClearBitMask(Status2Reg,0x08);

    status = PcdComRC522(PCD_TRANSCEIVE,ucComRC522Buf,9,ucComRC522Buf,&unLen);
    
    if ((status == MI_OK) && (unLen == 0x18))
    {   status = MI_OK;  }
    else
    {   status = MI_ERR;    }

    return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：验证卡片密码
//参数说明: auth_mode[IN]: 密码验证模式
//                 0x60 = 验证A密钥
//                 0x61 = 验证B密钥 
//          addr[IN]：块地址
//          pKey[IN]：密码
//          pSnr[IN]：卡片序列号，4字节
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////               
char PcdAuthState(unsigned char auth_mode,unsigned char addr,unsigned char *pKey,unsigned char *pSnr)
{
    char status;
    unsigned int  unLen;
    unsigned char i,ucComRC522Buf[MAXRLEN]; 

    ucComRC522Buf[0] = auth_mode;
    ucComRC522Buf[1] = addr;
    for (i=0; i<6; i++)
    {    ucComRC522Buf[i+2] = *(pKey+i);   }
    for (i=0; i<6; i++)
    {    ucComRC522Buf[i+8] = *(pSnr+i);   }
 //   memcpy(&ucComRC522Buf[2], pKey, 6); 
 //   memcpy(&ucComRC522Buf[8], pSnr, 4); 
    
    status = PcdComRC522(PCD_AUTHENT,ucComRC522Buf,12,ucComRC522Buf,&unLen);
    if ((status != MI_OK) || (!(RC522_Read(Status2Reg) & 0x08)))
    {   status = MI_ERR;   }
    
    return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：读取M1卡一块数据
//参数说明: addr[IN]：块地址
//          pData[OUT]：读出的数据，16字节
//返    回: 成功返回MI_OK
///////////////////////////////////////////////////////////////////// 
char PcdRead(unsigned char addr,unsigned char *pData)
{
    char status;
    unsigned int  unLen;
    unsigned char i,ucComRC522Buf[MAXRLEN]; 

    ucComRC522Buf[0] = PICC_READ;
    ucComRC522Buf[1] = addr;
    CalulateCRC(ucComRC522Buf,2,&ucComRC522Buf[2]);
   
    status = PcdComRC522(PCD_TRANSCEIVE,ucComRC522Buf,4,ucComRC522Buf,&unLen);
    if ((status == MI_OK) && (unLen == 0x90))
    {
        for (i=0; i<16; i++)
        {    *(pData+i) = ucComRC522Buf[i];   }
    }
    else
    {   status = MI_ERR;   }
    
    return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：写数据到M1卡一块
//参数说明: addr[IN]：块地址
//          pData[IN]：写入的数据，16字节
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////                  
char PcdWrite(unsigned char addr,unsigned char *pData)
{
    char status;
    unsigned int  unLen;
    unsigned char i,ucComRC522Buf[MAXRLEN]; 
    
    ucComRC522Buf[0] = PICC_WRITE;
    ucComRC522Buf[1] = addr;
    CalulateCRC(ucComRC522Buf,2,&ucComRC522Buf[2]);
 
    status = PcdComRC522(PCD_TRANSCEIVE,ucComRC522Buf,4,ucComRC522Buf,&unLen);

    if ((status != MI_OK) || (unLen != 4) || ((ucComRC522Buf[0] & 0x0F) != 0x0A))
    {   status = MI_ERR;   }
        
    if (status == MI_OK)
    {
        //memcpy(ucComRC522Buf, pData, 16);

        for (i=0; i<16; i++)
        {    ucComRC522Buf[i] = *(pData+i);   }
        CalulateCRC(ucComRC522Buf,16,&ucComRC522Buf[16]);

        status = PcdComRC522(PCD_TRANSCEIVE,ucComRC522Buf,18,ucComRC522Buf,&unLen);
        if ((status != MI_OK) || (unLen != 4) || ((ucComRC522Buf[0] & 0x0F) != 0x0A))
        {   status = MI_ERR;   }
    }
    
    return status;
}



/////////////////////////////////////////////////////////////////////
//功    能：命令卡片进入休眠状态
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////
char PcdHalt(void)
{
    unsigned int  unLen;
    unsigned char ucComRC522Buf[MAXRLEN]; 

    ucComRC522Buf[0] = PICC_HALT;
    ucComRC522Buf[1] = 0;
    CalulateCRC(ucComRC522Buf,2,&ucComRC522Buf[2]);
 
    PcdComRC522(PCD_TRANSCEIVE,ucComRC522Buf,4,ucComRC522Buf,&unLen);

    return MI_OK;
}

/////////////////////////////////////////////////////////////////////
//用RC522计算CRC16函数
/////////////////////////////////////////////////////////////////////
void CalulateCRC(unsigned char *pIndata,unsigned char len,unsigned char *pOutData)
{
    unsigned char i,n;
    ClearBitMask(DivIrqReg,0x04);
    RC522_Write(CommandReg,PCD_IDLE);
    SetBitMask(FIFOLevelReg,0x80);
    for (i=0; i<len; i++)
    {   RC522_Write(FIFODataReg, *(pIndata+i));   }
    RC522_Write(CommandReg, PCD_CALCCRC);
    i = 0xFF;
    do 
    {
        n = RC522_Read(DivIrqReg);
        i--;
    }
    while ((i!=0) && !(n&0x04));
    pOutData[0] = RC522_Read(CRCResultRegL);
    pOutData[1] = RC522_Read(CRCResultRegM);
}

/////////////////////////////////////////////////////////////////////
//功    能：复位RC522
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////
char PcdReset(void)
{
    RST_H;
    delay_ms(1);
    RST_L;
    delay_ms(1);
    RST_H;
    delay_ms(10);
	
    if(RC522_Read(0x02) == 0x80)
    {
        
    }

    RC522_Write(CommandReg,PCD_RESETPHASE);
    
    RC522_Write(ModeReg,0x3D);            //和Mifare卡通讯，CRC初始值0x6363
    RC522_Write(TReloadRegL,30);           
    RC522_Write(TReloadRegH,0);
    RC522_Write(TModeReg,0x8D);
    RC522_Write(TPrescalerReg,0x3E);
    RC522_Write(TxAutoReg,0x40);     
    return MI_OK;
}
//////////////////////////////////////////////////////////////////////
//设置RC632的工作方式 
//////////////////////////////////////////////////////////////////////
char M500PcdConfigISOType(unsigned char type)
{
   if (type == 'A')                     //ISO14443_A
   { 
       ClearBitMask(Status2Reg,0x08);

 /*     RC522_Write(CommandReg,0x20);    //as default   
       RC522_Write(ComIEnReg,0x80);     //as default
       RC522_Write(DivlEnReg,0x0);      //as default
	   RC522_Write(ComIrqReg,0x04);     //as default
	   RC522_Write(DivIrqReg,0x0);      //as default
	   RC522_Write(Status2Reg,0x0);//80    //trun off temperature sensor
	   RC522_Write(WaterLevelReg,0x08); //as default
       RC522_Write(ControlReg,0x20);    //as default
	   RC522_Write(CollReg,0x80);    //as default
*/
       RC522_Write(ModeReg,0x3D);//3F
/*	   RC522_Write(TxModeReg,0x0);      //as default???
	   RC522_Write(RxModeReg,0x0);      //as default???
	   RC522_Write(TxControlReg,0x80);  //as default???

	   RC522_Write(TxSelReg,0x10);      //as default???
   */
       RC522_Write(RxSelReg,0x86);//84
 //      RC522_Write(RxThresholdReg,0x84);//as default
 //      RC522_Write(DemodReg,0x4D);      //as default

 //      RC522_Write(ModWidthReg,0x13);//26
       RC522_Write(RFCfgReg,0x7F);   //4F
	/*   RC522_Write(GsNReg,0x88);        //as default???
	   RC522_Write(CWGsCfgReg,0x20);    //as default???
       RC522_Write(ModGsCfgReg,0x20);   //as default???
*/
   	   RC522_Write(TReloadRegL,30);//tmoLength);// TReloadVal = 'h6a =tmoLength(dec) 
	   RC522_Write(TReloadRegH,0);
       RC522_Write(TModeReg,0x8D);
	   RC522_Write(TPrescalerReg,0x3E);
	   

  //     PcdSetTmo(106);
	   delay_ms(1);
       PcdAntennaOn();
   }
   else{ return (char)-1; }
   
   return MI_OK;
}
/////////////////////////////////////////////////////////////////////
//功    能：置RC522寄存器位
//参数说明：reg[IN]:寄存器地址
//          mask[IN]:置位值
/////////////////////////////////////////////////////////////////////
void SetBitMask(unsigned char reg,unsigned char mask)  
{
    char tmp = 0x0;
    tmp = RC522_Read(reg);
    RC522_Write(reg,tmp | mask);  // set bit mask
}

/////////////////////////////////////////////////////////////////////
//功    能：清RC522寄存器位
//参数说明：reg[IN]:寄存器地址
//          mask[IN]:清位值
/////////////////////////////////////////////////////////////////////
void ClearBitMask(unsigned char reg,unsigned char mask)  
{
    char tmp = 0x0;
    tmp = RC522_Read(reg);
    RC522_Write(reg, tmp & ~mask);  // clear bit mask
} 

/////////////////////////////////////////////////////////////////////
//功    能：通过RC522和ISO14443卡通讯
//参数说明：Command[IN]:RC522命令字
//          pInData[IN]:通过RC522发送到卡片的数据
//          InLenByte[IN]:发送数据的字节长度
//          pOutData[OUT]:接收到的卡片返回数据
//          *pOutLenBit[OUT]:返回数据的位长度
/////////////////////////////////////////////////////////////////////
char PcdComRC522(unsigned char Command, 
                 unsigned char *pInData, 
                 unsigned char InLenByte,
                 unsigned char *pOutData, 
                 unsigned int  *pOutLenBit)
{
    char status = MI_ERR;
    unsigned char irqEn   = 0x00;
    unsigned char waitFor = 0x00;
    unsigned char lastBits;
    unsigned char n;
    unsigned int i;
    switch (Command)
    {
       case PCD_AUTHENT:
          irqEn   = 0x12;
          waitFor = 0x10;
          break;
       case PCD_TRANSCEIVE:
          irqEn   = 0x77;
          waitFor = 0x30;
          break;
       default:
         break;
    }
   
    RC522_Write(ComIEnReg,irqEn|0x80);
    ClearBitMask(ComIrqReg,0x80);
    RC522_Write(CommandReg,PCD_IDLE);
    SetBitMask(FIFOLevelReg,0x80);
    
    for (i=0; i<InLenByte; i++) RC522_Write(FIFODataReg, pInData[i]);
    RC522_Write(CommandReg, Command);
    
    if (Command == PCD_TRANSCEIVE)  SetBitMask(BitFramingReg,0x80);
    i = 2000;   //根据时钟频率调整，操作M1卡最大等待时间25ms
    do 
    {
         n = RC522_Read(ComIrqReg);
         i--;
    }
    while ((i!=0) && !(n&0x01) && !(n&waitFor));
    ClearBitMask(BitFramingReg,0x80);
	      
    if (i!=0)
    {    
         if(!(RC522_Read(ErrorReg)&0x1B))
         {
             status = MI_OK;
             if (n & irqEn & 0x01)
             {   status = MI_NOTAGERR;   }
             if (Command == PCD_TRANSCEIVE)
             {
               	n = RC522_Read(FIFOLevelReg);
              	lastBits = RC522_Read(ControlReg) & 0x07;
                if (lastBits)
                {   *pOutLenBit = (n-1)*8 + lastBits;   }
                else
                {   *pOutLenBit = n*8;   }
                if (n == 0)
                {   n = 1;    }
                if (n > MAXRLEN)
                {   n = MAXRLEN;   }
                for (i=0; i<n; i++)
                {   pOutData[i] = RC522_Read(FIFODataReg);    }
            }
         }
         else
         {   status = MI_ERR;   }
        
   }
   

   SetBitMask(ControlReg,0x80);           // stop timer now
   RC522_Write(CommandReg,PCD_IDLE); 
   return status;
}


/////////////////////////////////////////////////////////////////////
//开启天线  
//每次启动或关闭天险发射之间应至少有1ms的间隔
/////////////////////////////////////////////////////////////////////
void PcdAntennaOn()
{
    unsigned char i;
    i = RC522_Read(TxControlReg);
    if (!(i & 0x03))
    {
        SetBitMask(TxControlReg, 0x03);
    }
}


/////////////////////////////////////////////////////////////////////
//关闭天线
/////////////////////////////////////////////////////////////////////
void PcdAntennaOff()
{
    ClearBitMask(TxControlReg, 0x03);
}

//等待卡离开
void WaitCardOff(void)
{
	char          status;
    unsigned char	TagType[2];

	while(1)
	{
		status = PcdRequest(REQ_ALL, TagType);
		if(status)
		{
			status = PcdRequest(REQ_ALL, TagType);
			if(status)
			{
				status = PcdRequest(REQ_ALL, TagType);
				if(status)
				{
					return;
				}
			}
		}
		delay_ms(1000);
	}
}
